
#include <QtGui>
#include "highlighter.hpp"

Highlighter::Highlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent)
{
    this->variableFormat.setForeground(QColor(208, 32, 144));
    this->labelFormat.setForeground(QColor(208, 32, 144));
}


void Highlighter::initialize()
{
    QTextCharFormat numberFormat;
    QTextCharFormat commentFormat;
    QTextCharFormat functionFormat;

    HighlightingRule rule;

    // Functions
    functionFormat.setForeground(Qt::red);
    QStringList functionPatterns;
    QFile file(":/codecompletion/words");
    if (file.open(QFile::ReadOnly)) {
	rule.format = functionFormat;
	while (!file.atEnd()) {
	    QByteArray line = file.readLine().trimmed();
	    if (!line.isEmpty()) {
		QList<QByteArray> splitted = line.split(',');
		rule.pattern = QRegExp("\\b" + splitted[0].trimmed().toUpper() + "\\b");
		this->highlightingRules.append(rule);
		rule.pattern = QRegExp("\\b" + splitted[0].trimmed().toLower() + "\\b");
		this->highlightingRules.append(rule);

		if(splitted.size() == 2)
		    emit customTooltip(splitted.at(0).trimmed().toLower(), splitted.at(1).trimmed());
	    }
	}
    }

    // Numbers
    numberFormat.setForeground(Qt::darkBlue);
    QStringList numberPatterns;
    numberPatterns << "\\b[0-9][0-9a-fA-F]{,2}[h]\\b" << "\\b[0-9]{1,3}[d]\\b" << "\\b[01]{4}((\\s)?([01]{4})*)?[b]\\b" << "\\b[0-9]{1,}\\b";

    foreach(QString pattern, numberPatterns) {
	rule.pattern = QRegExp(pattern);
	rule.format = numberFormat;
	this->highlightingRules.append(rule);
    }

    // Comments
    commentFormat.setForeground(Qt::green);
    rule.pattern = QRegExp(";[^\n]*");
    rule.format = commentFormat;
    this->highlightingRules.append(rule);
}

void Highlighter::highlightBlock(const QString &text)
{
    QList<HighlightingRule> temp = this->highlightingRules;
    temp << this->additionalRules;

    foreach(HighlightingRule rule, temp) {
        QRegExp expression(rule.pattern);
        int index = text.indexOf(expression);
        while (index >= 0) {
            int length = expression.matchedLength();
            setFormat(index, length, rule.format);
            index = text.indexOf(expression, index + length);
        }
    }
}


void Highlighter::addCustomHighlightingRule(QString s, int type)
{
    QRegExp regexp = QRegExp("\\b" + s + "\\b");

    foreach(HighlightingRule rule, this->additionalRules) {
        if (rule.pattern == regexp)
            return;
    }

    HighlightingRule newRule;
    newRule.pattern = regexp;

    if (type == 0)
	newRule.format = this->variableFormat;
    else
	newRule.format = this->labelFormat;

    this->additionalRules.append(newRule);
}


void Highlighter::reset() {
    this->additionalRules.clear();
}
